import cv2
import numpy as np
import onnxruntime as ort


def preprocess_image(img_path, target_size=320):
    img = cv2.imread(img_path)
    if img is None:
        raise FileNotFoundError(f"Image not found: {img_path}")
    h, w = img.shape[:2]
    scale = min(target_size / w, target_size / h)
    new_w, new_h = int(w * scale), int(h * scale)
    resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
    top = (target_size - new_h) // 2
    bottom = target_size - new_h - top
    left = (target_size - new_w) // 2
    right = target_size - new_w - left
    padded = cv2.copyMakeBorder(resized, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(114, 114, 114))
    blob = padded.astype(np.float32) / 255.0
    blob = np.transpose(blob, (2, 0, 1))
    blob = np.expand_dims(blob, axis=0)
    return blob


if __name__ == "__main__":
    onnx_path = r"D:\NCNN\ncnn-20230816-windows-vs2017\x64\bin\202510161157\best31n.onnx"
    img_path = r"C:\TestPic\test-onnx\detect_20250927_103320_1758940400649.jpg"

    blob = preprocess_image(img_path, target_size=320)
    print("✅ Blob shape:", blob.shape)
    print("✅ Blob dtype:", blob.dtype)

    ort_session = ort.InferenceSession(onnx_path)
    input_name = ort_session.get_inputs()[0].name
    print(f"\n📥 ONNX Input Name: '{input_name}'")
    print(f"📏 Expected Input Shape: {ort_session.get_inputs()[0].shape}")

    outputs = ort_session.run(None, {input_name: blob})

    print(f"\n📤 Number of Outputs: {len(outputs)}")
    for i, out in enumerate(outputs):
        print(f"   Output {i} Shape: {out.shape}")
        if out.size > 0:
            flat = out.flatten()
            print(f"   Output {i} Sample (first 7 values): {flat[:7]}")
            print(f"   Output {i} Min/Max: {flat.min():.2f} / {flat.max():.2f}")